package com.dq.service.address;

import com.dq.domain.address.Address;
import com.dq.repository.address.AddressRepository;
import com.dq.service.ShiroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @创建人 gewenzhen
 * @创建时间 2019/10/24
 * @描述
 */
@Service
public class AddressService {
    @Autowired
    ShiroService shiroService;
    @Autowired
    AddressRepository addressRepository;

    public Address addOrModifyAddress(Address address) {
        address.setUser(shiroService.getUser());
        if (address.getIsDefault() != null && address.getIsDefault()) {
            List<Address> addresses = addressRepository.findByUserAndDeletedFalseAndIsDefaultTrue(shiroService.getUser());
            if (!addresses.isEmpty()) {
                addresses.forEach(address1 -> {
                    address1.setIsDefault(false);
                    addressRepository.save(address1);
                });
            }
        }
        return addressRepository.save(address);
    }
}
